package com.wechat.order.controller.weChatController;

import com.google.common.collect.Maps;
import com.wechat.order.config.ConstantConfig.ProjectUrl;
import com.wechat.order.config.ConstantConfig.WeChatAccountConfig;
import com.wechat.order.constant.RedisConstant;
import com.wechat.order.enums.MakeCodeEnum;
import com.wechat.order.platform.webScoket.WebSocket;
import com.wechat.order.util.CookieUtil;
import com.wechat.order.util.MakeOrderNum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 微信模拟或中介入口
 * 1、生成二维码提示扫码登陆，附带链接和客户端真实IP，启动socketio；
  2、微信扫码后调用服务器接口回传IP，socketio发送IP信息，提示此IP客户端跳转，返回登陆成功信息；
 *
 * Created by zzy on 2017/12/20.
 */
@Controller
@RequestMapping("/fake/weChat")
@Slf4j
public class FakeWeChatController {

    @Autowired
    private ProjectUrl projectUrl;

    @Autowired
    private WeChatAccountConfig weChatAccountConfig;

    @Autowired
    private MakeOrderNum makeOrderNum;
    @Autowired
    private WebSocket webSocket;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 登陆页面代理
     */
    @GetMapping("/login")
    public ModelAndView login(HttpServletRequest request){
      String loginUrl=  projectUrl.getLoginUrl();
      String weChatLoginConfirmUrl= weChatAccountConfig.getLoginConfirm();//微信确认页面
        //生成客户端编号
      String clientNum= makeOrderNum.makeOrderNum(MakeCodeEnum.CLIENT_NUM.getCode());
      //重定向到扫码页面
      String resultUrl=  loginUrl .concat("?url=")
              .concat(weChatLoginConfirmUrl)
              .concat("&param=")
              .concat("clientNum=")
              .concat(clientNum);
       return new ModelAndView("redirect:".concat(resultUrl)
              );
    }

    /**
     * 二维码扫描页面
     * @param url
     * @param param
     * @return
     */
    @GetMapping("/login/encode")
    public ModelAndView loginEncode(@RequestParam("url") String url,
                                    @RequestParam(value = "param",required = false,defaultValue = "") String param){

        Map<String,Object> model= Maps.newHashMap();
        if(!StringUtils.isEmpty(param)){
            url=url.concat("?").concat(param);
        }
        String codeUrl=projectUrl.getORcodeUrl();
        model.put("url",codeUrl.concat("?url=").concat(url));
        return new ModelAndView("index/homeIndex",model);
    }

    @RequestMapping("/login/wc/encode")
    public ModelAndView loginWcEncode(@RequestParam("clientNum") String clientNum,
                                      @RequestParam(value = "isAllow",required = false,defaultValue = "false") boolean isAllow,
                                      Map model){
       log.info("客户端编号={}",clientNum);

           model.put("clientNum",clientNum);
           return new ModelAndView("/index/weChatLoginResult");

    }

    @RequestMapping("/login/wc/encode/allow")
    @ResponseBody
    public Map loginWcEncodeAllow(@RequestParam("clientNum") String clientNum,
                                      @RequestParam(value = "isAllow",required = false,defaultValue = "false") boolean isAllow,
                                      Map model
                                    ){
        log.info("客户端编号={}",clientNum);
        if(isAllow){
            webSocket.sendMessage("loginAllow,".concat(clientNum));
            model.put("success",true);
        }
        return model;
    }

    @GetMapping("/login/verify")
    public ModelAndView loginVerify(@RequestParam("clientNum") String clientNum,Map model,
                                    HttpServletResponse response){
        //发布登陆通过通知
        String token = UUID.randomUUID().toString();
        Integer expire= RedisConstant.LOGIN_EXPIRE;
        //2、设置token至redis
        stringRedisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX,token),clientNum,expire, TimeUnit.SECONDS);
        //3、设置token至cookie
        CookieUtil.set(response,"token",token,expire);
        return new ModelAndView("redirect:http://zzyrestful.natapp1.cc/sell/seller/order/list");
    }
}
